﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using KeepAccounts.Common.Utilities;

namespace KeepAccounts.Common.Jwt
{
    public static class TokenHelper
    {
        public static string CreateJwtToken(string userId, int clientIdentityType)
        {
            //var setting = ManagerConfig.GetManagerSection("JwtSettings");

            #region 设置用户角色
            var Role = string.Empty;
            if (clientIdentityType == 1)
                Role = "Manager";
            #endregion

            //var jwtSettings = Newtonsoft.Json.JsonConvert.DeserializeObject<JwtSettings>(setting);
            var jwtSettings = ManagerConfig.GetManagerSection<JwtSettings>("JwtSettings");
            var signingKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                claims: new List<Claim> {
                    new Claim(JwtRegisteredClaimNames.Jti, userId),
                    new Claim("ClientIdentityType", clientIdentityType.ToString()),
                    new Claim(ClaimTypes.Role,Role)
                },
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(15),
                signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }


        /// <summary>
        /// 解密token
        /// </summary>
        public static string DecryptToken(string token)
        {
            var jwtSecurity = new JwtSecurityTokenHandler();
            if (!jwtSecurity.CanReadToken(token))
            {
                throw new Exception("token有误");
            }

            var jwttoken = jwtSecurity.ReadJwtToken(token);
            var userid = jwttoken.Claims.FirstOrDefault(s => s.Type == JwtRegisteredClaimNames.Jti).Value;
            var exp = jwttoken.Claims.FirstOrDefault(s => s.Type == JwtRegisteredClaimNames.Exp).Value;

            var expTime = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(exp));
            if (expTime < DateTime.Now.AddDays(-20))
            {
                throw new Exception("token已过时");
            }
            return userid;
        }
    }
}
